<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form ref="formEditGeneralUnitBasicRef" :model="formData" :size="layoutStore.defaultFormItemSize"
        :rules="rules" label-width="120px" label-position="right" @submit.prevent>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="单位名称" prop="GeneralUnitBasic.dwmc">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.dwmc" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位英文名称" prop="GeneralUnitBasic.dwywmc">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.dwywmc" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位简称" prop="GeneralUnitBasic.dwjc">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.dwjc" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位英文简称" prop="GeneralUnitBasic.dwywjc">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.dwywjc" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位简拼" prop="GeneralUnitBasic.dwjp">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.dwjp" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位地址" prop="GeneralUnitBasic.dwdz">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.dwdz" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隶属单位号" prop="GeneralUnitBasic.lsdwh">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.lsdwh" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位类别" prop="GeneralUnitBasic.dwlbm">
              <el-select class="input-item" v-model="formData.GeneralUnitBasic.dwlbm" placeholder="" :clearable="true"
                :filterable="true" @visible-change="dwlbmWidget.onVisibleChange">
                <el-option v-for="item in dwlbmWidgetDropdownList" :key="item.id" :label="item.itemName"
                  :value="item.itemId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位办别" prop="GeneralUnitBasic.dwbbm">

              <el-select class="input-item" v-model="formData.GeneralUnitBasic.dwbbm" placeholder="" :clearable="true"
                :filterable="true" @visible-change="dwbbmWidget.onVisibleChange">
                <el-option v-for="item in dwbbmWidgetDropdownList" :key="item.id" :label="item.itemName"
                  :value="item.itemId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位有效标识" prop="GeneralUnitBasic.dwyxbs">
              <el-input-number class="input-item" v-model="formData.GeneralUnitBasic.dwyxbs" placeholder=""
                :clearable="true" :step="1" :controls="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否实体" prop="GeneralUnitBasic.sfst">
               <el-select class="input-item" v-model="formData.GeneralUnitBasic.sfst" placeholder="" :clearable="true"
                :filterable="true" @visible-change="sfstWidget.onVisibleChange">
                <el-option v-for="item in sfstWidgetDropdownList" :key="item.id" :label="item.itemName"
                  :value="item.itemId" />
              </el-select>
           
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建立年月" prop="GeneralUnitBasic.jlny">
              <el-date-picker class="input-item" v-model="formData.GeneralUnitBasic.jlny" type="month" placeholder=""
                :clearable="true" format="YYYY-MM" value-format="YYYY-MM" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人事单位号" prop="GeneralUnitBasic.rsdwh">
              <el-input class="input-item" v-model="formData.GeneralUnitBasic.rsdwh" type="text" placeholder=""
                :clearable="true" :show-word-limit="false" maxlength="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构类别" prop="GeneralUnitBasic.jglbm">
              <el-select class="input-item" v-model="formData.GeneralUnitBasic.jglbm" placeholder="" :clearable="true"
                :filterable="true" @visible-change="jglbmWidget.onVisibleChange">
                <el-option v-for="item in jglbmWidgetDropdownList" :key="item.id" :label="item.itemName"
                  :value="item.itemId" />
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary"
        @click="onSubmitGeneralUnitBasicClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditGeneralUnitBasic',
};
</script>

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { GeneralUnitBasicData } from '@/api/generated/generalUnitBasicController';
import { GeneralUnitBasicController } from '@/api/generated';
import { GlobalDictItemCmeduController } from '@/api/generated';
import { SysGlobalDictController } from '@/api/system';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
    id?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    id: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

const formEditGeneralUnitBasicRef = ref();
// 表单数据定义
type FormEditGeneralUnitBasicData = {
  GeneralUnitBasic: GeneralUnitBasicData;
};
// 表单数据
const formData = reactive<FormEditGeneralUnitBasicData>({
  GeneralUnitBasic: {
    // ID
    id: undefined,
    // 单位号
    dwh: undefined,
    // 单位名称
    dwmc: undefined,
    // 单位英文名称
    dwywmc: undefined,
    // 单位简称
    dwjc: undefined,
    // 单位英文简称
    dwywjc: undefined,
    // 单位简拼
    dwjp: undefined,
    // 单位地址
    dwdz: undefined,
    // 隶属单位号
    lsdwh: undefined,
    // 单位类别码
    dwlbm: undefined,
    // 单位办别码
    dwbbm: undefined,
    // 单位有效标识
    dwyxbs: undefined,
    // 是否实体
    sfst: undefined,
    // 建立年月
    jlny: undefined,
    // 人事单位号
    rsdwh: undefined,
    // 机构类别码
    jglbm: undefined,
    // 创建时间
    createTime: undefined,
    // 更新时间
    updateTime: undefined,
    // 创建用户
    createUserId: undefined,
    // 更新用户
    updateUserId: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'GeneralUnitBasic.jglbm': [
    { required: true, message: '请输入机构类别码', trigger: 'blur' }
  ],
  'GeneralUnitBasic.rsdwh': [
  ],
  'GeneralUnitBasic.dwyxbs': [
    { required: true, message: '请输入单位有效标识', trigger: 'blur' }
  ],
  'GeneralUnitBasic.dwywmc': [
  ],
  'GeneralUnitBasic.dwjc': [
    { required: true, message: '请输入单位简称', trigger: 'blur' }
  ],
  'GeneralUnitBasic.sfst': [
    { required: true, message: '请输入是否实体', trigger: 'blur' }
  ],
  'GeneralUnitBasic.dwmc': [
    { required: true, message: '请输入单位名称', trigger: 'blur' }
  ],
  'GeneralUnitBasic.jlny': [
  ],
  'GeneralUnitBasic.dwdz': [
  ],
  'GeneralUnitBasic.lsdwh': [
  ],
  'GeneralUnitBasic.dwywjc': [
  ],
  'GeneralUnitBasic.dwjp': [
  ],
  'GeneralUnitBasic.dwlbm': [
  ],
  'GeneralUnitBasic.dwbbm': [
  ],
});
const instance = getCurrentInstance();

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};

const isEdit = computed(() => {
  return props.saveOnSubmit ? props.id != null : props.rowData != null;
});

// 初始化页面数据
const loadGeneralUnitBasicData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.GeneralUnitBasic = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    GeneralUnitBasicController.view(params).then(res => {
      formData.GeneralUnitBasic = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 单位类别码下拉数据获取函数
 */
const loadDwlbmDropdownList = (): Promise<any> => {
  return new Promise((resolve, reject) => {
    const params = {
      globalDictItemCmeduDtoFilter: {
        dictCode: "UnitCategory"
      }

    };
    GlobalDictItemCmeduController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 单位类别码配置参数
const dwlbmOptions: DropdownOptions<DictData> = {
  loadData: loadDwlbmDropdownList,
  isTree: false,
};
// 单位类别码下拉组件
const dwlbmWidget = useDropdown(dwlbmOptions);
const { dropdownList: dwlbmWidgetDropdownList } = dwlbmWidget


const loadDwbbmDropdownList = (): Promise<any> => {
  return new Promise((resolve, reject) => {
    const params = {
      globalDictItemCmeduDtoFilter: {
        dictCode: "UnitFound"
      }

    };
    GlobalDictItemCmeduController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};

const dwbbmWidgetOptions: DropdownOptions<DictData> = {
  loadData: loadDwbbmDropdownList,
  isTree: false,
};
const dwbbmWidget = useDropdown(dwbbmWidgetOptions);
const { dropdownList: dwbbmWidgetDropdownList } = dwbbmWidget

const loadjglbmDropdownList = (): Promise<any> => {
  return new Promise((resolve, reject) => {
    const params = {
      globalDictItemCmeduDtoFilter: {
        dictCode: "InstitutionType"
      }

    };
    GlobalDictItemCmeduController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
const jglbmWidgetOptions: DropdownOptions<DictData> = {
  loadData: loadjglbmDropdownList,
  isTree: false,
};

const jglbmWidget = useDropdown(jglbmWidgetOptions);
const { dropdownList: jglbmWidgetDropdownList } = jglbmWidget

const loadsfstDropdownList = (): Promise<any> => {
  return new Promise((resolve, reject) => {
    const params = {
      globalDictItemCmeduDtoFilter: {
        dictCode: "isShiTi"
      }

    };
    GlobalDictItemCmeduController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
const sfstWidgetOptions: DropdownOptions<DictData> = {
  loadData: loadsfstDropdownList,
  isTree: false,
};
const sfstWidget = useDropdown(sfstWidgetOptions);
const { dropdownList: sfstWidgetDropdownList } = sfstWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditGeneralUnitBasic = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditGeneralUnitBasic = () => {
  refreshFormEditGeneralUnitBasic();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditGeneralUnitBasic();
};
/**
 * 保存
 */
const onSubmitGeneralUnitBasicClick = () => {
  formEditGeneralUnitBasicRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.GeneralUnitBasic
      };
      retFormData.dwlbmDictMap = findItemFromList(dwlbmWidgetDropdownList.value, retFormData.dwlbm, 'id');

      retFormData.dwbbmDictMap = findItemFromList(dwbbmWidgetDropdownList.value, retFormData.dwbbm, 'id');

      retFormData.jglbmDictMap = findItemFromList(jglbmWidgetDropdownList.value, retFormData.jglbm, 'id');

        retFormData.sfstDictMap = findItemFromList(sfstWidgetDropdownList.value, retFormData.sfst, 'id');
      props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      generalUnitBasicDto: {
        id: formData.GeneralUnitBasic.id,
        dwh: formData.GeneralUnitBasic.dwh,
        dwmc: formData.GeneralUnitBasic.dwmc,
        dwywmc: formData.GeneralUnitBasic.dwywmc,
        dwjc: formData.GeneralUnitBasic.dwjc,
        dwywjc: formData.GeneralUnitBasic.dwywjc,
        dwjp: formData.GeneralUnitBasic.dwjp,
        dwdz: formData.GeneralUnitBasic.dwdz,
        lsdwh: formData.GeneralUnitBasic.lsdwh,
        dwlbm: formData.GeneralUnitBasic.dwlbm,
        dwbbm: formData.GeneralUnitBasic.dwbbm,
        dwyxbs: formData.GeneralUnitBasic.dwyxbs,
        sfst: formData.GeneralUnitBasic.sfst,
        jlny: formData.GeneralUnitBasic.jlny,
        rsdwh: formData.GeneralUnitBasic.rsdwh,
        jglbm: formData.GeneralUnitBasic.jglbm,
        createTime: formData.GeneralUnitBasic.createTime,
        updateTime: formData.GeneralUnitBasic.updateTime,
        createUserId: formData.GeneralUnitBasic.createUserId,
        updateUserId: formData.GeneralUnitBasic.updateUserId,
      }
    };

    let httpCall = isEdit.value ? GeneralUnitBasicController.update : GeneralUnitBasicController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadGeneralUnitBasicData().then(res => {
    dwlbmWidget.onVisibleChange(true).catch(e => { console.error(e) });

    dwbbmWidget.onVisibleChange(true).catch(e => { console.error(e) });

    jglbmWidget.onVisibleChange(true).catch(e => { console.error(e) });
    sfstWidget.onVisibleChange(true).catch(e => { console.error(e) });
    if (isEdit.value) refreshFormEditGeneralUnitBasic();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

onMounted(() => {
  formInit();
});
</script>
